package com.wyl.studyjavaxvalidation.controller;

import com.wyl.studyjavaxvalidation.dto.PersonDto;
import com.wyl.studyjavaxvalidation.util.ValidList;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import javax.validation.constraints.NotBlank;
import java.util.List;

/**
 * @author 吴宇亮 on 2021/12/20 11:31
 */
@RestController
@RequestMapping("/person")
public class PersonController {

    @PostMapping("/add")
    public String add(@RequestBody @Valid PersonDto personDto, BindingResult result){
        if (result.hasErrors()) {
            return result.getFieldError().getDefaultMessage();
        }
        System.out.println(personDto);
        return personDto.toString();
    }

    // valid对List这种不生效：https://blog.csdn.net/onceing/article/details/110119877
    @PostMapping("/addList")
    public String add(@RequestBody @Valid ValidList<PersonDto> personDtoList, BindingResult result){
        if (result.hasErrors()) {
            return result.getFieldError().getDefaultMessage();
        }
        System.out.println(personDtoList);
        return personDtoList.toString();
    }

    // 怎么对String进行校验？
    @PostMapping("/addByName")
    public String add(@RequestParam(value = "name") @NotBlank(message = "name不能为空") String name){
        return name;
    }

}
